package com.mes.utils.zebra;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.zebra.sdk.comm.Connection;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.comm.TcpConnection;

public class ZebraPrintUtils {

	public static void main(String[] args) {
//		try {
			HashMap<String, Object> map = new HashMap<>();
			map.put("batchNo", "****");
			sendZplOverTcp("172.25.3.224", "^XA ^MMF ^PW1446 ^LL0827 ^LS0 ^FT556,369^A0N,83,81^FH^FD${batchNo}^FS ^WVN ^RFW,H,1,10,1^FD40002343^FS ^PQ1,0,1,Y^XZ", "abcaaa", map);
			sendZplOverTcp("172.25.3.224", "^XA\n" + 
					"^MMF\n" + 
					"^PW1446\n" + 
					"^LL0827\n" + 
					"^LS0\n" + 
					"^FT114,321^A0N,83,81^FH\n^FDbatch:ronald测试^FS\n" + 
					"^FT322,319^A0N,83,81^FH\n^FDabce-213123^FS\n" + 
					"^PQ1,0,1,Y^XZ", "abcaaa", map);
//		} catch (ConnectionException e) {
//			e.printStackTrace();
//		}
	}
	
	public static void sendZplOverTcp(String ip, String zplData, Map<String, Object> param) {
		sendZplOverTcp(ip, zplData, null, param);
	}
	
	public static void sendZplOverTcp(String ip, String zplData, String rfidStr, Map<String, Object> param) {
		// Instantiate connection for ZPL TCP port at given address
		Connection conn = new TcpConnection(ip, TcpConnection.DEFAULT_ZPL_TCP_PORT);
		// Open the connection - physical connection is established here.
		try {
			conn.open();
			
			//设置rfid到芯片
			if(StringUtils.isNotEmpty(rfidStr)) {
//				if(rfidStr.length() > 16) {
//					rfidStr = rfidStr.substring(0, 16);
//				} else if(rfidStr.length() < 16) {
//					rfidStr = StringUtils.rightPad(rfidStr, 16, ' ');
//				}
				String astring = StringConvertUtils.stringToAscii(rfidStr);
				StringBuilder newEpc = new StringBuilder(astring.replace(",", ""));
				String rfidZpl = "^RFW,H,1,10,1^FD4000" + newEpc.toString() + "^FS";
				int pqLen = zplData.lastIndexOf("^PQ");
				zplData = zplData.substring(0, pqLen) + rfidZpl + zplData.substring(pqLen);
			}
            zplData = replaceVar(zplData, param);
            System.err.println("zpl指令：" + zplData);
			conn.write(zplData.getBytes());
		} catch (ConnectionException e) {
			e.printStackTrace();
			throw new RuntimeException("打印机连接异常：" + ip);
		} finally {
			try {
				if(conn != null) {
					conn.close();
				}
			} catch (ConnectionException e) {
				e.printStackTrace();
			}
		}

	}
	
	private static String replaceVar(String zplData, Map<String, Object> param) {
		if(param != null) {
			for (String key : param.keySet()) {
				zplData = zplData.replace("${" + key + "}", param.get(key).toString());
			}
		}
		return zplData;
	}
}
